<template>
  <div>
    <van-field v-model="msg">
      <template #button>
        <van-button type="info" @click="btnClick">发送</van-button>
      </template>
    </van-field>
    <van-button @click="closeEvent">关闭</van-button>
  </div>
</template>
<script>
export default {
  data () {
    return {
      ws: '',
      msg: ''
    }
  },
  created () {
    // 1:建立连接
    this.ws = new WebSocket('ws://zllhyy.cn:4430')
    // 2:监听是否连接成功
    this.ws.addEventListener('open', () => {
      console.log('连接成功')
    })
    // 3:可以接收消息
    this.ws.addEventListener('message', e => {
      console.log('服务端发送的消息：', e.data)
    })
    // 关闭的监听
    this.ws.addEventListener('close', () => {
      console.log('关闭成功')
    })
  },
  methods: {
    btnClick () {
      // 4:发送消息
      this.ws.send(this.msg)
    },
    closeEvent () {
      this.ws.close()
    }
  }
}
</script>
<style></style>
